package com.fowo.api.syncAmazon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.entity.*;
import com.fowo.api.mapper.*;
import com.fowo.api.syncAmazon.api.OrderService;
import com.fowo.api.syncAmazon.mapper.AmazonTmpMapper;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SalesStatementServiceImpl extends ServiceImpl<AmazonSalesStatementMapper, AmazonSalesStatement> {

    @Resource
    private TmpSalesStatementMapper tmpSalesStatementMapper;
    @Resource
    private OrderService orderService;
    @Resource
    private AmazonTmpMapper amazonTmpMapper;

    public void syncSalesStatement() throws Exception {
        //清空临时表
        amazonTmpMapper.deleteAllSalesStatement();
        //拉取数据到临时表
        orderService.getOrderReport();

        //获取临时表数据
        List<TmpSalesStatement> statements = tmpSalesStatementMapper.selectList(new QueryWrapper<TmpSalesStatement>().eq("del_flag", 0));
        List<AmazonSalesStatement> insertList = new ArrayList<>();
        if(statements != null && statements.size() > 0){
            for (TmpSalesStatement statement:statements) {
                //去重
                QueryWrapper<AmazonSalesStatement> orderWrapper = new QueryWrapper<>();
                orderWrapper.eq("del_flag",0);
                orderWrapper.eq("amazon_order_id",statement.getAmazonOrderId());
                orderWrapper.eq("msku",statement.getMsku());
                int count = (int)this.count(orderWrapper);
                if(count > 0){
                    continue;
                }
                AmazonSalesStatement salesStatement = new AmazonSalesStatement();
                BeanUtils.copyProperties(statement,salesStatement);
                salesStatement.setId(null);
                salesStatement.setCreateTime(new Date());
                insertList.add(salesStatement);
            }
            Lists.partition(insertList,200);
            for (List<AmazonSalesStatement> list:Lists.partition(insertList,200)) {
                this.saveBatch(list);
            }
        }
    }

}
